<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btnList="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            v-model:data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                class="not-mongolia"
                type="input"
                placeholder="请选择仓库"
                :disabled="true"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="selectDepot"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <PageFilter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct()"
                >添加产品</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct()"
                >删除产品</el-button
              >
            </template>
            <template v-slot:filter-batchHandle>
              <el-input-number
                v-model="filterInfo.data.lowLevel"
                controls-position="right"
                style="width: 100px"
                placeholder="低水位"
                :step="1"
                :min="0"
                :max="9999999"
              />
              <el-button @click="batchLowLevel()">批量设置低水位</el-button>
              <el-input-number
                v-model="filterInfo.data.highLevel"
                controls-position="right"
                style="width: 100px"
                placeholder="高水位"
                :step="1"
                :min="0"
                :max="9999999"
              />
              <el-button @click="batchHighLevell()">批量设置高水位</el-button>
            </template>
          </PageFilter>
          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :api="tableInfo.api"
                :pager="false"
                :tabIndex="true"
                v-model:query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber || '-' }}</p>
                  <p>{{ scope.row.brandName || '-' }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template v-slot:col-defaultSupplierName="scope">
                  <p>{{ scope.row.defaultSupplierName || '-' }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.productCategoryValue || '-' }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
              </PageTable>
            </el-form>
            <!-- 选择仓库 -->
            <SelectDepot
              v-if="selectDepotInfo.visible"
              v-model:show-dialog="selectDepotInfo.visible"
              :check-box="false"
              :highlight-row="true"
              :saveEmpty="true"
              :query="selectDepotInfo.query"
              :isLock="false"
              @callback="selectDepotCallback"
            />
            <!-- 选择产品 -->
            <selectProduct
              v-if="selectProductInfo.visible"
              v-model:show-dialog="selectProductInfo.visible"
              v-model:query="selectProductInfo.query"
              :show-supplier-name="selectProductInfo.showSupplierName"
              :showCheckBox="true"
              @callback="selectProductCallback"
            />
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="stockHighLowWarningConfigModify">
import {
  warningStockConfigDetailAll,
  warningStockConfigAll,
  createWarningStockConfig,
  updateWarningStockConfig,
} from '@/api/warning'

const { proxy } = getCurrentInstance()
const props = defineProps(['title', 'visible', 'tableRow'])
const formRefs = ref(undefined)
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'batchHandle' },
  ],
  data: {
    lowLevel: 0,
    highLevel: 0,
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: warningStockConfigDetailAll,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      minWidth: '150px',
    },
    {
      label: '供应商名称',
      value: 'defaultSupplierName',
      type: 'slot',
      minWidth: '150px',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    // {label: '是否启用低水位', value: 'lowLevelEnable', type: 'slot'},
    { label: '包装规格', value: 'packingSpecification', type: 'column' },
    { label: '低水位', value: 'lowLevel', type: 'number2' },
    // {label: '是否启用高水位', value: 'highLevelEnable', type: 'slot'},
    { label: '高水位', value: 'highLevel', type: 'number2' },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: '220px',
    },
  ],
})
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    depotName: '',
    depotId: '',
  },
  fieldList: [
    { label: '仓库', value: 'depotName', type: 'slot' },

    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    depotName: [{ required: true, message: '请选择仓库', blur: 'change' }],
  },
  labelWidth: '120px',
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 1,
    idNot: '',
  },
})
const selectProductInfo = ref({
  visible: false,
  showSupplierName: true,
  query: {},
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections != 0
})
const canAddProduct = computed(() => {
  return formInfo.value.data.depotName
})
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function batchLowLevel() {
  if (tableInfo.value.selections && tableInfo.value.selections.length) {
    tableInfo.value.selections.forEach((item) => {
      item.lowLevel = filterInfo.value.data.lowLevel
    })
  } else {
    proxy.$message.warning('请勾选数据')
  }
}
function batchHighLevell() {
  if (tableInfo.value.selections && tableInfo.value.selections.length) {
    tableInfo.value.selections.forEach((item) => {
      item.highLevel = filterInfo.value.data.highLevel
    })
  } else {
    proxy.$message.warning('请勾选数据')
  }
}

//添加产品
function addProduct() {
  const productIdNotIn = tableInfo.value.data.map((row) => row.productId)
  selectProductInfo.value.query.idNotIn = productIdNotIn.toString()
  selectProductInfo.value.query.hasStockDepotId = formInfo.value.data.depotId
  selectProductInfo.value.visible = true
}
function selectProductCallback(data) {
  tableInfo.value.data = tableInfo.value.data.concat(
    data.map((item) => {
      return {
        ...item,
        lowLevelEnable: true,
        highLevelEnable: true,
        lowLevel: 0,
        highLevel: 0,
        productId: item.id,
        defaultSupplierId: item.supplierId,
        defaultSupplierName: item.supplierName,
        defaultSupplierCode: item.supplierCode,
        defaultSupplierPrice: item.price,
      }
    })
  )
}
//删除产品
function removeProduct() {
  tableInfo.value.data = tableInfo.value.data.filter(
    (row) => !tableInfo.value.selections.includes(row)
  )
}
//选择仓库
function selectDepot() {
  warningStockConfigAll().then((res) => {
    if (res && res.success) {
      let ids = []
      if (res.data && res.data.length) {
        ids = res.data.map((item) => item.depotId)
      }
      selectDepotInfo.value.query.idNot = ids.length ? ids.toString() : ''
      selectDepotInfo.value.visible = true
    }
  })
}
function selectDepotCallback(data) {
  formInfo.value.data.depotName = data.name
  formInfo.value.data.depotId = data.id
}
//保存
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    // if (valid) {
    const data = formInfo.value.data
    if (parseInt(data.lowLevel) >= parseInt(data.highLevel)) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '默认低水位 应该小于 默认高水位',
      })
      return
    }
    const api = data.id ? updateWarningStockConfig : createWarningStockConfig
    let commonName = tableInfo.value.data
      .filter((item) => parseInt(item.lowLevel) >= parseInt(item.highLevel))
      .map((item) => item.commonName)
    if (commonName.length) {
      proxy.$alert(`产品【${commonName}】低水位应该小于高水位`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    const details = tableInfo.value.data.filter((row) => row.productId)
    data.details = details

    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        proxy.$emit('returnModify')
      }
    })

    // }
  })
}
onMounted(() => {
  proxy.$nextTick(() => {
    if (Object.keys(props.tableRow).length) {
      formInfo.value.data = { ...props.tableRow }
      filterInfo.value.query.warningStockConfigId = props.tableRow.id
      getList()
    }
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})
</script>

<style scoped></style>
